package cn.trigram.structure;

import java.io.Serializable;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

/**
 * 树节点 可以实现树的遍历算法
 * <ol>
 *   <li>一定最好实现equals & hashCode 方法</li>
 *   <li>如果需要对树进行复制性质的操作，请实现clone方法</li>
 * </ol>
 *
 * @author 一日看尽长安花
 * @date 2022/01/12 22:03:00
 */
public abstract class TreeNode implements Serializable, Cloneable {

  protected TreeNode parent;

  protected List<TreeNode> children;

  public TreeNode getParent() {

    return parent;
  }

  public void setParent(TreeNode parent) {

    this.parent = parent;
  }

  public List<TreeNode> getChildren() {

    return children;
  }

  public void setChildren(List<TreeNode> children) {

    this.children = children;
  }


  /**
   * 是否是叶子节点
   */
  public boolean isLeaf() {

    return CollectionUtils.isEmpty(this.children);
  }

  public boolean isRoot() {

    return !this.hasParent();
  }

  /**
   * 是否有父节点
   */
  public abstract boolean hasParent();

  /**
   * 是否是给定节点的父节点
   */
  public abstract boolean isParent(TreeNode node);

  /**
   * 判断相等
   */
  public abstract boolean equalsTo(TreeNode node);

  public TreeNode clone() {

    try {
      return (TreeNode)super.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    return null;
  }

}
